#include "phone_fly.h"
#include "Comm/console.h"
#include "Comm/settingsdialog.h"
#include "OpenGL/glwidget.h"
#include <QMessageBox>
#include <QtSerialPort/QSerialPort>
#include <QVBoxLayout>
#include <QSpinBox>

Phone_fly::Phone_fly(QWidget *parent)
	: QMainWindow(parent)
{
	ui->setupUi(this);
    QHBoxLayout* layout = new QHBoxLayout(this);
    QHBoxLayout* layout2 = new QHBoxLayout(this);
    
	openGL = new GLWidget();
	

    console = new Console;
    console->setEnabled(true);
//! [1]
    serial = new QSerialPort(this);
//! [1]
    settings = new SettingsDialog;

	
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionQuit->setEnabled(true);
    ui->actionConfigure->setEnabled(true);
    ui->actionShowBoundary->setEnabled(true);
	
	
    layout->addWidget(openGL);
    layout2->addWidget(console);
	
    ui->widget->setLayout(layout);
    //ui->widget2->setLayout(layout2);
	
    initActionsConnections();

    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(handleError(QSerialPort::SerialPortError)));

//! [2]
    connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
//! [2]
    connect(console, SIGNAL(getData(QByteArray)), this, SLOT(writeData(QByteArray)));
	
	connect(ui->actionController, SIGNAL(toggled(bool)), this, SLOT(setController(bool)));
	/*
    connect(ui->dsb1, SIGNAL(valueChanged(double)), this, SLOT(setA(double)));
    connect(ui->dsb2, SIGNAL(valueChanged(double)), this, SLOT(setB(double)));
    connect(ui->dsb3, SIGNAL(valueChanged(double)), this, SLOT(setC(double)));
    connect(ui->dsb4, SIGNAL(valueChanged(double)), this, SLOT(setD(double)));
	*/



	
}

Phone_fly::~Phone_fly()
{
	
}

void Phone_fly::openSerialPort()
{
    SettingsDialog::Settings p = settings->settings();
    serial->setPortName(p.name);
    serial->setBaudRate(p.baudRate);
    serial->setDataBits(p.dataBits);
    serial->setParity(p.parity);
    serial->setStopBits(p.stopBits);
    serial->setFlowControl(p.flowControl);
    if (serial->open(QIODevice::ReadWrite)) {
            console->setEnabled(true);
            console->setLocalEchoEnabled(p.localEchoEnabled);
            ui->actionConnect->setEnabled(false);
            ui->actionDisconnect->setEnabled(true);
            ui->actionConfigure->setEnabled(false);
            ui->statusBar->showMessage(tr("Connected to %1 : %2, %3, %4, %5, %6")
                                       .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                                       .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));
    } else {
        QMessageBox::critical(this, tr("Error"), serial->errorString());

        ui->statusBar->showMessage(tr("Open error"));
    }
}


void Phone_fly::closeSerialPort()
{
    serial->close();
    console->setEnabled(false);
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionConfigure->setEnabled(true);
    ui->statusBar->showMessage(tr("Disconnected"));
}

void Phone_fly::about()
{
    QMessageBox::about(this, tr("About Simple Terminal"),
                       tr("The <b>Simple Terminal</b> example demonstrates how to "
                          "use the Qt Serial Port module in modern GUI applications "
                          "using Qt, with a menu bar, toolbars, and a status bar."));
}

void Phone_fly::writeData(const QByteArray &data)
{
    serial->write(data);
}


void Phone_fly::readData()
{
        QByteArray data = serial->readAll();
        QString myValue(data);
        QStringList split =  myValue.split(" ");
        int k ;
        for(int i = 0; i < split.size(); i++){
            console->putData(split[i].toLatin1());
            if(split[i].size() > 1){
                switch(k = split[i].at(0).toLatin1()){
                case 'a':
                    split[i].remove(0,1);
                    openGL->setValue(0,split[i].toInt());
                    break;
                case 'b':
                    split[i].remove(0,1);
                    openGL->setValue(1,split[i].toInt());
                    break;
                case 'c':
                    split[i].remove(0,1);
                    openGL->setValue(2,split[i].toInt());
                    break;
                case 'd':
                    split[i].remove(0,1);
                    openGL->setValue(3,split[i].toInt());
                    break;
                case 'e':
                    split[i].remove(0,1);
                    openGL->setValue(4,split[i].toInt());
                    break;
                case 'f':
                    split[i].remove(0,1);
                    openGL->setValue(5,split[i].toInt());
                    break;
                case 'r': //reset message
                    split[i].remove(0,1);
					openGL->command(split[i].toInt());
                    break;
                case 'o': // change cotrol object
                    split[i].remove(0,1);
                    openGL->setNowControl(split[i].toInt());
                    break;
                case 'n':
                    split[i].remove(0,1);
                    openGL->setFingerFactor(split[i].toInt());
                    break;
                case 'g':
                    split[i].remove(0,1);
                    openGL->setPoseFactor(GLWidget::POSE_AZIMUTH, split[i].toFloat());
                    break;
                case 'h':
                    split[i].remove(0,1);
                    openGL->setPoseFactor(GLWidget::POSE_PITCH, split[i].toFloat());
                    break;
                case 'i':
                    split[i].remove(0,1);
                    openGL->setPoseFactor(GLWidget::POSE_ROLL, split[i].toFloat());
                    break;
                }
            }
            console->putData("\n");
        }
}

void Phone_fly::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        QMessageBox::critical(this, tr("Critical Error"), serial->errorString());
        closeSerialPort();
    }
}



void Phone_fly::setBoundaryVisible(bool is){
    openGL->setBoundaryVisible(is);
}

void Phone_fly::initActionsConnections()
{
    connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(openSerialPort()));
    connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(closeSerialPort()));
    connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionConfigure, SIGNAL(triggered()), settings, SLOT(updateAndShow()));
    connect(ui->actionClear, SIGNAL(triggered()), console, SLOT(clear()));
    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));
    connect(ui->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui->actionShowBoundary, SIGNAL(triggered(bool)), this, SLOT(setBoundaryVisible(bool)));

}


void Phone_fly::setController(bool is){
	openGL->setControllerMode(is);
}
